<?php

namespace admin\modules\product\models\forms;

use yii\base\Model;

class FormMaterial extends Model
{
    public $product_id;
    public $content;

    public function attributeLabels()
    {
        return [
            'product_id' => '产品ID',
            'content' => '素材内容',
        ];
    }

    public function rules()
    {
        return [
            ['product_id', 'required'],
            ['content', 'required'],
            ['product_id', 'exist', 'targetClass' => Products::class, 'targetAttribute' => 'id'],
            ['content', 'string', 'min' => 20, 'max' => 2000000],
        ];
    }

    public function saveMaterial()
    {
        $product = Products::findOne($this->product_id);
        $type4Metial = $product->type4Material;
        if (!$type4Metial) {
            $type4Metial = new ProductMaterials();
            $type4Metial->product_id = $this->product_id;
            $type4Metial->material_type = ProductMaterials::TYPE_RICH_TEXT;
        }
        $type4Metial->content = $this->content;
        if (!$type4Metial->save()) {
            return false;
        }
        return true;
    }
}
